// DOM 元素
const loginPage = document.getElementById('login-page');
const app = document.getElementById('app');
const loginForm = document.getElementById('login-form');
const navItems = document.querySelectorAll('.nav-item');
const pageContents = document.querySelectorAll('.page-content');
const publishTypeModal = document.getElementById('publish-type-modal');
const postModal = document.getElementById('post-modal');
const closeModal = document.getElementById('close-modal');
const publishButtons = {
    nav: document.getElementById('nav-publish'),
    lost: document.getElementById('add-lost-btn'),
    found: document.getElementById('add-found-btn')
};
const publishOptions = {
    lost: document.getElementById('publish-lost'),
    found: document.getElementById('publish-found')
};
const modalTitle = document.getElementById('modal-title');
const postType = document.getElementById('post-type');
const postForm = document.getElementById('post-form');
const uploadContainer = document.getElementById('upload-container');
const itemImage = document.getElementById('item-image');
const imagePreview = document.getElementById('image-preview');
const previewImg = document.getElementById('preview-img');
const itemDetailModal = document.getElementById('item-detail-modal');
const closeDetailModal = document.getElementById('close-detail-modal');
const detailContent = document.getElementById('detail-content');
const contactModal = document.getElementById('contact-modal');
const closeContactModal = document.getElementById('close-contact-modal');
const contactForm = document.getElementById('contact-form');
const tabs = document.querySelectorAll('.tab-btn');
const filterButtons = document.querySelectorAll('.filter-btn');
const myPostsContainer = document.getElementById('my-posts-container');
const notificationsContainer = document.getElementById('notifications-container');
const markAllRead = document.getElementById('mark-all-read');
const logoutBtn = document.getElementById('logout-btn');
const lostSearch = document.getElementById('lost-search');
const foundSearch = document.getElementById('found-search');
const lostItemsContainer = document.getElementById('lost-items');
const foundItemsContainer = document.getElementById('found-items');
const myLostCount = document.getElementById('my-lost-count');
const myFoundCount = document.getElementById('my-found-count');

// 登录相关元素
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const togglePassword = document.getElementById('toggle-password');
const rememberMe = document.getElementById('remember-me');
const forgotPassword = document.getElementById('forgot-password');
const forgotPasswordModal = document.getElementById('forgot-password-modal');
const closeForgotModal = document.getElementById('close-forgot-modal');
const forgotPasswordForm = document.getElementById('forgot-password-form');
const loginButton = document.getElementById('login-button');
const usernameError = document.getElementById('username-error');
const passwordError = document.getElementById('password-error');
const loginError = document.getElementById('login-error');
const registerLink = document.getElementById('register-link');
const resetButton = document.getElementById('reset-button');
const forgotError = document.getElementById('forgot-error');

// 登录功能
function initLogin() {
    // 密码显示/隐藏切换
    togglePassword.addEventListener('click', () => {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        togglePassword.innerHTML = type === 'password' ? '<i class="fa fa-eye text-gray-400"></i>' : '<i class="fa fa-eye-slash text-gray-400"></i>';
    });

    // 表单提交处理
    loginForm.addEventListener('submit', handleLogin);

    // 忘记密码

    forgotPassword.addEventListener('click', (e) => {
        e.preventDefault();
        showError('忘记密码功能尚未开放，请联系管理员', loginError);
    });



    // 注册链接
    registerLink.addEventListener('click', (e) => {
        e.preventDefault();
        showError('注册功能尚未开放，请联系管理员', loginError);
    });
}

// 登录处理函数
function handleLogin(e) {
    e.preventDefault();

    // 重置错误信息
    resetErrors();

    // 获取表单值
    const username = usernameInput.value.trim();
    const password = passwordInput.value.trim();
    const remember = rememberMe.checked;

    // 表单验证
    let isValid = true;

    if (!username) {
        showError('请输入用户名', usernameError, usernameInput);
        isValid = false;
    }

    if (!password) {
        showError('请输入密码', passwordError, passwordInput);
        isValid = false;
    } else if (password.length < 6) {
        showError('密码长度至少为6位', passwordError, passwordInput);
        isValid = false;
    }

    if (!isValid) return;

    // 显示加载状态
    showLoading(true, loginButton);

    // 模拟登录请求
    setTimeout(() => {
        // 模拟登录验证
        if (username === 'testuser' && password === 'password') {

            // 切换到主应用
            loginPage.classList.add('hidden');
            app.classList.remove('hidden');
            loadDashboard();
        } else {
            // 显示登录错误
            showError('用户名或密码错误，请重试', loginError);
        }

        // 隐藏加载状态
        showLoading(false, loginButton);
    }, 1500);
}

// 显示错误信息
function showError(message, element = loginError, input = null) {
    if (element) {
        element.textContent = message;
        element.classList.remove('hidden');

        if (input) {
            input.classList.add('border-danger', 'shake');
            setTimeout(() => {
                input.classList.remove('shake');
            }, 500);
        }
    }
}

// 显示成功信息
function showSuccess(message, element) {
    if (element) {
        element.textContent = message;
        element.classList.remove('hidden', 'bg-red-50', 'text-red-700');
        element.classList.add('bg-green-50', 'text-green-700');
    }
}

// 重置错误信息
function resetErrors() {
    [usernameError, passwordError, loginError, forgotError].forEach(el => {
        if (el) {
            el.textContent = '';
            el.classList.add('hidden');
            el.classList.remove('bg-green-50', 'text-green-700');
        }
    });

    [usernameInput, passwordInput].forEach(input => {
        if (input) input.classList.remove('border-danger');
    });
}

// 显示加载状态
function showLoading(isLoading, button) {
    if (button) {
        button.disabled = isLoading;
        if (isLoading) {
            button.innerHTML = '<span class="loading-spinner"></span> 处理中...';
        } else {
            if (button === loginButton) {
                button.textContent = '登录';
            } else if (button === resetButton) {
                button.textContent = '发送重置链接';
            }
        }
    }
}



// 检查登录状态
function checkLoginStatus() {
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';

    if (isLoggedIn) {
        loginPage.classList.add('hidden');
        app.classList.remove('hidden');
        loadDashboard();
    }
}

// 导航功能
navItems.forEach(item => {
    item.addEventListener('click', (e) => {
        e.preventDefault();
        const page = item.getAttribute('data-page');
        showPage(page);
    });
});

// 显示特定页面
function showPage(pageName) {
    pageContents.forEach(page => {
        page.classList.add('hidden');
    });
    navItems.forEach(item => {
        item.classList.remove('nav-active');
        item.classList.add('nav-inactive');
    });
    const activePage = document.getElementById(pageName);
    const activeNav = document.querySelector(`.nav-item[data-page="${pageName}"]`);
    if (activePage && activeNav) {
        activePage.classList.remove('hidden');
        activeNav.classList.remove('nav-inactive');
        activeNav.classList.add('nav-active');
    }
    // 根据页面加载相应内容
    if (pageName === 'dashboard') {
        loadDashboard();
    } else if (pageName === 'lost') {
        loadLostItems();
        setupLostSearch();
    } else if (pageName === 'found') {
        loadFoundItems();
        setupFoundSearch();
    } else if (pageName === 'my-page') {
        loadMyPage();
    }
}

// 加载仪表盘数据
function loadDashboard() {
    // 更新统计数据
    document.getElementById('current-lost-count').textContent = stats.currentLost;
    document.getElementById('current-found-count').textContent = stats.currentFound;
    document.getElementById('recovered-count').textContent = stats.recovered;
    document.getElementById('recovery-rate').textContent = stats.recoveryRate;

    // 加载最近发布
    const recentPosts = document.getElementById('recent-posts');
    recentPosts.innerHTML = '';
    const allItems = [...lostItems, ...foundItems].sort((a, b) => new Date(b.date) - new Date(a.date));
    allItems.slice(0, 3).forEach(item => {
        const card = createItemCard(item);
        recentPosts.appendChild(card);
    });

    // 加载月度统计表格
    const statsTableBody = document.getElementById('stats-table-body');
    statsTableBody.innerHTML = '';
    monthlyStats.forEach(stat => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap">${stat.month}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stat.lost}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stat.found}</td>
            <td class="px-6 py-4 whitespace-nowrap">${stat.recovered}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${parseInt(stat.rate) > 30 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                    ${stat.rate}
                </span>
            </td>
        `;
        statsTableBody.appendChild(row);
    });
}

// 创建物品卡片
function createItemCard(item) {
    const card = document.createElement('div');
    card.className = 'bg-white rounded-xl overflow-hidden card-shadow clickable-card';
    card.innerHTML = `
        <div class="flex">
            <div class="w-24 h-24 bg-gray-100 flex-shrink-0">
                <img src="${item.image}" alt="${item.name}" class="w-full h-full object-cover">
            </div>
            <div class="flex-1 p-4">
                <div class="flex justify-between items-start">
                    <h3 class="font-medium text-lg">${item.name}</h3>
                    <span class="px-2 py-1 text-xs rounded-full ${item.type === 'lost' ? 'bg-primary/10 text-primary' : 'bg-secondary/10 text-secondary'}">
                        ${item.type === 'lost' ? '寻物' : '招领'}
                    </span>
                </div>
                <p class="text-gray-500 text-sm mt-1 line-clamp-2">${item.description}</p>
                <div class="flex justify-between items-center mt-2">
                    <span class="text-xs text-gray-400">${item.date}</span>
                    <span class="text-xs text-gray-500">${item.location}</span>
                </div>
            </div>
        </div>
    `;
    card.addEventListener('click', () => showItemDetail(item));
    return card;
}

// 加载寻物列表
function loadLostItems() {
    lostItemsContainer.innerHTML = '';
    lostItems.forEach(item => {
        const card = createItemCard(item);
        lostItemsContainer.appendChild(card);
    });
}

// 加载寻主列表
function loadFoundItems() {
    foundItemsContainer.innerHTML = '';
    foundItems.forEach(item => {
        const card = createItemCard(item);
        foundItemsContainer.appendChild(card);
    });
}

// 设置寻物搜索功能
function setupLostSearch() {
    lostSearch.addEventListener('input', () => {
        filterItems(lostItems, lostSearch.value.trim().toLowerCase(), lostItemsContainer);
    });
}

// 设置寻主搜索功能
function setupFoundSearch() {
    foundSearch.addEventListener('input', () => {
        filterItems(foundItems, foundSearch.value.trim().toLowerCase(), foundItemsContainer);
    });
}

// 过滤物品列表
function filterItems(items, searchTerm, container) {
    if (!searchTerm) {
        container.innerHTML = '';
        items.forEach(item => {
            const card = createItemCard(item);
            container.appendChild(card);
        });
        return;
    }

    const filteredItems = items.filter(item =>
        item.name.toLowerCase().includes(searchTerm) ||
        item.description.toLowerCase().includes(searchTerm) ||
        item.location.toLowerCase().includes(searchTerm)
    );

    container.innerHTML = '';
    if (filteredItems.length === 0) {
        container.innerHTML = `
            <div class="bg-white rounded-xl p-4 card-shadow text-center">
                <p class="text-gray-500">没有找到匹配的物品</p>
            </div>
        `;
    } else {
        filteredItems.forEach(item => {
            const card = createItemCard(item);
            container.appendChild(card);
        });
    }
}

// 加载我的页面
function loadMyPage() {
    // 更新我的发布数量
    myLostCount.textContent = userPosts.filter(post => post.type === 'lost').length;
    myFoundCount.textContent = userPosts.filter(post => post.type === 'found').length;

    // 加载我的发布
    loadMyPosts('all');

    // 加载通知
    loadNotifications();
}

// 加载我的发布
function loadMyPosts(filter = 'all') {
    myPostsContainer.innerHTML = '';
    let filteredPosts = userPosts;
    if (filter !== 'all') {
        filteredPosts = userPosts.filter(post => post.type === filter);
    }

    filteredPosts.forEach(post => {
        const card = document.createElement('div');
        card.className = 'bg-white rounded-lg p-3 card-shadow';
        card.innerHTML = `
            <div class="flex justify-between items-start">
                <div class="flex items-center">
                    <div class="w-10 h-10 bg-gray-100 rounded-lg flex-shrink-0">
                        <img src="${post.image}" alt="${post.name}" class="w-full h-full object-cover rounded-lg">
                    </div>
                    <div class="ml-3">
                        <h4 class="font-medium text-sm">${post.name}</h4>
                        <p class="text-xs text-gray-500">${post.date}</p>
                    </div>
                </div>
                <div class="flex space-x-2">
                    <span class="px-2 py-0.5 text-xs rounded-full ${post.status === 'active' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'}">
                        ${post.status === 'active' ? '进行中' : '已找回'}
                    </span>
                    <button class="text-gray-400 hover:text-gray-600 smooth-transition edit-btn" data-id="${post.id}">
                        <i class="fa fa-edit"></i>
                    </button>
                </div>
            </div>
        `;
        myPostsContainer.appendChild(card);
    });
}

// 编辑帖子
function editPost(id) {
    const post = userPosts.find(p => p.id === id);
    if (post) {
        openPostModal(post.type, post);
    }
}

// 加载通知
function loadNotifications() {
    notificationsContainer.innerHTML = '';
    notifications.forEach(notification => {
        const card = document.createElement('div');
        card.className = `bg-white rounded-lg p-3 card-shadow ${!notification.read ? 'border-l-4 border-primary' : ''}`;
        card.innerHTML = `
            <div class="flex justify-between">
                <p class="text-sm ${!notification.read ? 'font-medium' : 'text-gray-500'}">${notification.content}</p>
                <span class="text-xs text-gray-400">${notification.date}</span>
            </div>
        `;
        notificationsContainer.appendChild(card);
    });
}

// 显示物品详情
function showItemDetail(item) {
    detailContent.innerHTML = `
        <div class="mb-4">
            <img src="${item.image}" alt="${item.name}" class="w-full h-48 object-cover rounded-lg">
        </div>
        <div class="flex justify-between items-center mb-2">
            <h3 class="text-xl font-bold">${item.name}</h3>
            <span class="px-2 py-1 text-xs rounded-full ${item.type === 'lost' ? 'bg-primary/10 text-primary' : 'bg-secondary/10 text-secondary'}">
                ${item.type === 'lost' ? '寻物' : '招领'}
            </span>
        </div>
        <div class="mb-4">
            <p class="text-gray-600">${item.description}</p>
        </div>
        <div class="grid grid-cols-2 gap-4 mb-4">
            <div class="bg-gray-50 rounded-lg p-3">
                <p class="text-xs text-gray-500">丢失/捡到地点</p>
                <p class="font-medium">${item.location}</p>
            </div>
            <div class="bg-gray-50 rounded-lg p-3">
                <p class="text-xs text-gray-500">发布日期</p>
                <p class="font-medium">${item.date}</p>
            </div>
        </div>
        <div class="bg-gray-50 rounded-lg p-3 mb-4">
            <p class="text-xs text-gray-500">联系方式</p>
            <p class="font-medium">${item.contact}</p>
        </div>
    `;
    document.getElementById('contact-item-id').value = item.id;
    itemDetailModal.classList.remove('hidden');
}

// 打开发布表单模态框
function openPostModal(type, post = null) {
    if (type === 'lost') {
        modalTitle.textContent = post ? '编辑寻物信息' : '发布寻物';
        postType.value = 'lost';
    } else {
        modalTitle.textContent = post ? '编辑招领信息' : '发布招领';
        postType.value = 'found';
    }

    // 清空表单
    postForm.reset();
    document.getElementById('edit-item-id').value = '';
    imagePreview.classList.add('hidden');

    // 如果是编辑模式，填充表单
    if (post) {
        document.getElementById('edit-item-id').value = post.id;
        document.getElementById('item-name').value = post.name;
        document.getElementById('item-description').value = post.description;
        document.getElementById('item-location').value = post.location;
        document.getElementById('contact-info').value = post.contact;
        if (post.image) {
            previewImg.src = post.image;
            imagePreview.classList.remove('hidden');
        }
    }

    postModal.classList.remove('hidden');
}

// 发布类型选择
publishButtons.nav.addEventListener('click', () => {
    publishTypeModal.classList.remove('hidden');
});

// 寻物页面的发布按钮直接打开寻物表单
publishButtons.lost.addEventListener('click', () => {
    openPostModal('lost');
});

// 寻主页面的发布按钮直接打开寻主表单
publishButtons.found.addEventListener('click', () => {
    openPostModal('found');
});

// 发布类型选择
publishOptions.lost.addEventListener('click', () => {
    publishTypeModal.classList.add('hidden');
    openPostModal('lost');
});

publishOptions.found.addEventListener('click', () => {
    publishTypeModal.classList.add('hidden');
    openPostModal('found');
});

// 关闭模态框
closeModal.addEventListener('click', () => {
    postModal.classList.add('hidden');
});

closeDetailModal.addEventListener('click', () => {
    itemDetailModal.classList.add('hidden');
});

closeContactModal.addEventListener('click', () => {
    contactModal.classList.add('hidden');
});

// 上传图片功能
function setupDragAndDrop() {
    const dropArea = uploadContainer;

    // 点击上传区域触发文件选择
    dropArea.addEventListener('click', () => {
        itemImage.click();
    });

    // 文件选择处理
    itemImage.addEventListener('change', (e) => {
        if (e.target.files && e.target.files[0]) {
            const file = e.target.files[0];
            if (isImageFile(file)) {
                previewFile(file);
            } else {
                alert('请选择图片文件 (JPG, PNG)');
                itemImage.value = '';
            }
        }
    });

    // 检查是否为图片文件
    function isImageFile(file) {
        return file.type.startsWith('image/');
    }

    // 预览文件
    function previewFile(file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            previewImg.src = e.target.result;
            imagePreview.classList.remove('hidden');
        }
        reader.readAsDataURL(file);
    }
}

// 提交表单
postForm.addEventListener('submit', (e) => {
    e.preventDefault();
    // 获取表单数据
    const type = postType.value;
    const name = document.getElementById('item-name').value;
    const description = document.getElementById('item-description').value;
    const location = document.getElementById('item-location').value;
    const contact = document.getElementById('contact-info').value;
    const image = previewImg.src || 'https://picsum.photos/300/200?random=7';
    const date = new Date().toISOString().split('T')[0]; // 获取当前日期
    const id = Date.now(); // 生成唯一ID
    const status = "active"; // 默认为进行中状态

    // 创建新物品对象
    const newItem = {
        id,
        name,
        description,
        location,
        contact,
        date,
        image,
        type,
        status,
        owner: "当前用户" // 实际项目中应获取当前登录用户
    };

    // 将新物品添加到公共数组
    if (type === 'lost') {
        lostItems.unshift(newItem);
    } else {
        foundItems.unshift(newItem);
    }

    // 将新物品添加到用户发布数组
    userPosts.unshift(newItem);

    // 更新统计数据
    stats[type === 'lost' ? 'currentLost' : 'currentFound'] = type === 'lost' ? lostItems.length : foundItems.length;

    // 模拟提交成功
    alert(`${type === 'lost' ? '寻物' : '招领'}信息发布成功！`);
    postModal.classList.add('hidden');

    // 刷新当前页面并显示新内容
    const currentPage = document.querySelector('.page-content:not(.hidden)');
    if (currentPage) {
        showPage(currentPage.id);
    }

    // 如果当前是我的页面，刷新我的发布
    if (currentPage && currentPage.id === 'my-page') {
        loadMyPage();
    }
});

// 联系失主/拾主
document.getElementById('contact-owner-btn').addEventListener('click', () => {
    itemDetailModal.classList.add('hidden');
    contactModal.classList.remove('hidden');
});

// 提交联系表单
contactForm.addEventListener('submit', (e) => {
    e.preventDefault();
    // 模拟提交表单
    const message = document.getElementById('contact-message').value;

    // 模拟提交成功
    alert('消息发送成功！对方将尽快与您联系。');
    contactModal.classList.add('hidden');
});

// 标签切换
tabs.forEach(tab => {
    tab.addEventListener('click', () => {
        tabs.forEach(t => {
            t.classList.remove('text-primary', 'border-primary');
            t.classList.add('text-gray-500');
        });
        tab.classList.remove('text-gray-500');
        tab.classList.add('text-primary', 'border-b-2', 'border-primary');

        const tabContent = document.getElementById(tab.getAttribute('data-tab'));
        document.getElementById('my-posts').classList.add('hidden');
        document.getElementById('notifications').classList.add('hidden');
        tabContent.classList.remove('hidden');
    });
});

// 过滤按钮
filterButtons.forEach(btn => {
    btn.addEventListener('click', () => {
        filterButtons.forEach(b => {
            b.classList.remove('bg-primary/10', 'text-primary');
            b.classList.add('bg-gray-100', 'text-gray-500');
        });
        btn.classList.remove('bg-gray-100', 'text-gray-500');
        btn.classList.add('bg-primary/10', 'text-primary');

        const filter = btn.getAttribute('data-filter');
        loadMyPosts(filter);
    });
});

// 标记所有通知为已读
markAllRead.addEventListener('click', () => {
    notifications.forEach(notification => {
        notification.read = true;
    });
    loadNotifications();
    alert('所有通知已标记为已读！');
});

// 登出
logoutBtn.addEventListener('click', () => {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('isLoggedIn');
        app.classList.add('hidden');
        loginPage.classList.remove('hidden');
        loginForm.reset();
        resetErrors();
    }
});

// 初始化页面
function init() {
    // 为统计卡片添加点击事件
    document.getElementById('current-lost-card').addEventListener('click', () => {
        showPage('lost');
    });

    document.getElementById('current-found-card').addEventListener('click', () => {
        showPage('found');
    });

    // 为我的页面标签添加点击事件
    document.getElementById('my-lost-tab').addEventListener('click', () => {
        showPage('my-page');
        document.querySelector('.tab-btn[data-tab="my-posts"]').click();
        document.querySelector('.filter-btn[data-filter="lost"]').click();
    });

    document.getElementById('my-found-tab').addEventListener('click', () => {
        showPage('my-page');
        document.querySelector('.tab-btn[data-tab="my-posts"]').click();
        document.querySelector('.filter-btn[data-filter="found"]').click();
    });

    document.getElementById('my-notifications-tab').addEventListener('click', () => {
        showPage('my-page');
        document.querySelector('.tab-btn[data-tab="notifications"]').click();
    });

    // 初始化拖放功能
    setupDragAndDrop();

    // 初始化登录功能
    initLogin();

    // 检查登录状态
    checkLoginStatus();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);